package v1

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"net/http"
	"server/logger"
	"time"
)

var (
	upgrader = websocket.Upgrader{
		ReadBufferSize:   1024,
		WriteBufferSize:  1024,
		CheckOrigin:      func(r *http.Request) bool { return true },
		HandshakeTimeout: time.Duration(time.Second * 5),
	}
)

func SocketLink(c *gin.Context) {
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		logger.Info("cant upgrade connection")
		return
	}
	var i = 0
	for {
		msgType, msgData, err := conn.ReadMessage()
		if err != nil {
			logger.Info("cant read message")
		}
		logger.Info(fmt.Sprintf("recv message: %s\n", msgData))
		i++
		err = conn.WriteMessage(msgType, []byte(fmt.Sprintf("%d", i)))
		if err != nil {
			logger.Info(err.Error())
		}
	}
}
